package com.example.forum.exception;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

/**
 * 功能描述:
 *  全局异常处理
 * @author Lenovo
 * @date 2024/12/11
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(ApplicationException.class)
    public AppResult applicationException(ApplicationException e){
        log.error("发成异常：e{}",e);
        if(e.getErrorResult() != null){
            return e.getErrorResult();
        }
        //非空校验
        if(e.getMessage() == null || e.getMessage().equals("")){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        //返回具体异常信息
        return AppResult.failed(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(HandlerMethodValidationException.class)
    public AppResult applicationException(HandlerMethodValidationException e){
        log.error("发成异常：e{}",e);
        return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public AppResult exception(Exception e){
        log.error("发成异常：e{}",e);
        if(e.getMessage() == null || e.getMessage().equals("")){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        return AppResult.failed(ResultCode.ERROR_SERVICES);
    }
}
